#include "mediactrl.h"


AW_VID_CAPTURE_HANDLE aw_cap_handle;
AW_VID_RENDER_HANDLE aw_render_handle;
AW_VID_ENCODER_HANDLE aw_encoder_handle;

int32_t vidCaptureCallback( struct MemoryFrame *frame, void *ctx ){
    int32_t ret = 0;

    ret = aw_vid_enc_deliver( aw_encoder_handle, frame );
    if( ret < 0 ){
        printf( "%s aw_vid_enc_deliver failed....\r\n", __FUNCTION__ );
    }
    return ret;
}

int32_t aw_mediactrl_init( int32_t w, int32_t h, int32_t fps, int32_t enc_bitrate ){

    int32_t ret = 0;

    CoderConfig enc_config = {
        .width = w,
        .height = h,
        .fps = fps,
        .bitrate = enc_bitrate,
    };

    ret = aw_vid_cap_init( w, h, &aw_cap_handle);
    if( ret < 0 ){
        printf( "%s aw_vid_cap_init failed:%d\r\n", ret );
    }

    ret = aw_vid_enc_init( enc_config, &aw_encoder_handle );
    if( ret < 0 ){
        printf( "%s aw_vid_enc_init failed:%d\r\n", ret );
    }
    return ret;
}

int32_t aw_mediactrl_deinit(){
    int32_t ret = 0;
    ret = aw_vid_cap_deinit(aw_cap_handle);
    if( ret < 0 ){
        printf( "%s aw_vid_cap_deinit failed:%d\r\n", ret );
    }

    ret = aw_vid_enc_deinit(aw_encoder_handle);
    if( ret < 0 ){
        printf( "%s aw_vid_enc_deinit failed:%d\r\n", ret );
    }
    return ret;
}


int32_t aw_mediactrl_start(){
    int32_t ret = 0;
    ret = aw_vid_enc_start( aw_encoder_handle );
    if( ret < 0 ){
        printf( "%s aw_mediactrl_start failed:%d\r\n", ret );
    }

    ret = aw_vid_cap_regcb(aw_cap_handle, vidCaptureCallback, NULL);
    if( ret < 0 ){
        printf( "%s aw_vid_cap_regcb failed:%d\r\n", ret );
    }

    ret = aw_vid_cap_start( aw_cap_handle );
    if( ret < 0 ){
        printf( "%s aw_vid_cap_start failed:%d\r\n", ret );
    }
    return ret;
}
int32_t aw_mediactrl_stop(){

    int32_t ret = 0;
    ret = aw_vid_cap_stop(aw_cap_handle);
    if( ret < 0 ){
        printf( "%s aw_mediactrl_stop failed:%d\r\n", ret );
    }

    ret = aw_vid_enc_stop( aw_encoder_handle );
    if( ret < 0 ){
        printf( "%s aw_vid_enc_stop failed:%d\r\n", ret );
    }
    return ret;
}

int32_t aw_mediactrl_regcb(VidEncoderCallback _cb, void *_ctx){
    int32_t ret = -1;
    if( _cb != NULL ){
        ret = aw_vid_enc_regcb( aw_encoder_handle, _cb, _ctx );
        if( ret < 0 ){
            printf( "%s aw_vid_enc_regcb failed:%d\r\n", ret );
        }
    }
    return ret;
}